<template>
  <div class="playedu-tree">
    <div
      :class="['mb-8 category-label', selectKey.length === 0 ? 'active' : '']"
      @click="handleSelect([], '')"
    >
      全部{{ text }}{{ showNum && userTotal ? `(${userTotal})` : '' }}
    </div>

    <a-tree
      v-if="treeData.length > 0"
      :tree-data="treeData"
      :selectedKeys="selectKey"
      :switcherIcon="() => h('i', { class: 'iconfont icon-icon-fold c-gray' })"
      @select="handleSelect"
      @expand="handleExpand"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, h } from "vue";
import { department } from "@/api";

// props
const props = defineProps<{
  text: string;
  showNum: boolean;
  selected: any[];
  refresh: boolean;
  onUpdate: (keys: any, title: any) => void;
}>();



// emits
const emit = defineEmits<{
  (e: "update", keys: any[], title: string): void;
}>();

// state
const treeData = ref<any[]>([]);
const selectKey = ref<any[]>([]);
const userTotal = ref(0);
const loading = ref(false);

// 部门缓存
let departments: Record<number, any[]> = {};
let depUserCount: Record<number, number> = {};

// 监听 selected 回显
watch(
  () => props.selected,
  (val) => {
    if (val && val.length > 0) {
      selectKey.value = val;
    }
  },
  { immediate: true }
);

// 监听 refresh
watch(
  () => props.refresh,
  () => {
    loadDepartments();
  },
  { immediate: true }
);

// 加载部门
async function loadDepartments() {
  loading.value = true;
  const res: any = await department.departmentList({});
  departments = res.data.departments;
  depUserCount = res.data.dep_user_count;
  userTotal.value = res.data.user_total;

  if (Object.keys(departments).length > 0) {
    treeData.value = props.showNum
      ? checkNewArr(departments, 0, depUserCount)
      : checkArr(departments, 0);
  } else {
    treeData.value = [{ key: "", title: "全部", children: [] }];
  }

  loading.value = false;
}

// 生成树 - 带人数
function checkNewArr(departments: any, id: number, counts: any) {
  const arr: any[] = [];
  for (const dep of departments[id] || []) {
    const hasChild = departments[dep.id];
    const node: any = {
      key: dep.id,
      title: getNewTitle(dep.name, dep.id, counts),
    };
    if (hasChild) {
      node.children = checkNewArr(departments, dep.id, counts);
    }
    arr.push(node);
  }
  return arr;
}

// 生成树 - 不带人数
function checkArr(departments: any, id: number) {
  const arr: any[] = [];
  for (const dep of departments[id] || []) {
    const hasChild = departments[dep.id];
    const node: any = {
      key: dep.id,
      title: h("span", { class: "tree-title-elli" }, dep.name),
    };
    if (hasChild) {
      node.children = checkArr(departments, dep.id);
    }
    arr.push(node);
  }
  return arr;
}

// 节点 title
function getNewTitle(title: string, id: number, counts: any) {
  const value = counts[id] || 0;
  return h("span", { class: "tree-title-elli" }, `${title}(${value})`);
}

// 点击
function handleSelect(selectedKeys: any, info: any) {
  let label = "全部" + props.text;
  if (info?.node?.title?.children) {
    label = info.node.title.children;
  }
  if (selectedKeys.length <= 1) {
    emit("update", selectedKeys, label);
    selectKey.value = selectedKeys;
  }
}

// 展开
function handleExpand(selectedKeys: any, info: any) {
  let label = "全部" + props.text;
  if (info?.node?.title?.children) {
    label = info.node.title.children;
  }
  if (selectedKeys.length <= 1) {
    emit("update", selectedKeys, label);
    selectKey.value = selectedKeys;
  }
}
</script>
